﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using DreamBuilder.UI.UserControls.DataAccess.Services;
using System.Data;
using DreamBuilder.DictionaryAccess;


namespace DreamBuilder.UI.UserControls.DataAccess.Components
{
    public class MsSqlUCEditDAL : UCEditDAL
    {
        public override DataTable GetEditControlsData(string EditID, System.Collections.Generic.List<VoucherEditItemInfo> list, string PKValue)
        {
            string sSql = "";
            string selectSql = "";
            string fromSql = "";
            VoucherTotalInfo pTotalInfo = DictionaryAccessFacade.GetVoucherTotalInfo(EditID);
            TableDicInfo mainTableDicInfo = DictionaryAccessFacade.GetTableDicInfo(pTotalInfo.MainTable);
            if (string.IsNullOrEmpty(pTotalInfo.TableConnectSql))
            {
                fromSql = pTotalInfo.MainTable;
            }
            else
            {
                fromSql = pTotalInfo.TableConnectSql;
            }
            list.ForSpecification<VoucherEditItemInfo>(
                delegate(VoucherEditItemInfo pEditItemInfo)
                   {
                       GetSelectFromSql(pEditItemInfo, ref selectSql, ref fromSql);
                   },
                   delegate(VoucherEditItemInfo pEditItemInfo)
                   {
                       return pEditItemInfo.Show == true ? true : false;
                   }
                );
            selectSql = selectSql.Substring(0, selectSql.Length - 1);
            sSql = "select " + selectSql + " from " + fromSql + " where " + mainTableDicInfo.TableCode + "." + mainTableDicInfo.PrimaryField + " = '" + PKValue + "' ";
            return DBHelper.ExecuteDataSet(sSql).Tables[0];
        }


        private void GetSelectFromSql(VoucherEditItemInfo pEditItemInfo, ref string selectSql, ref string fromSql)
        {
            string sTableCode = pEditItemInfo.TableCode.Trim();
            string sFieldCode = pEditItemInfo.FieldCode.Trim();
            FieldDicInfo pFieldDicInfo = DictionaryAccessFacade.GetFieldDicInfo(sTableCode, sFieldCode);

            if (pEditItemInfo.ItemType == EDITITEMTYPE.TYPE_ComboBoxReference || pEditItemInfo.ItemType == EDITITEMTYPE.TYPE_Reference || pEditItemInfo.ItemType == EDITITEMTYPE.TYPE_RadioList || pEditItemInfo.ItemType == EDITITEMTYPE.TYPE_CheckBoxList)
            {
                selectSql += sTableCode + "." + sFieldCode + " as '" + sTableCode + "." + sFieldCode + "',";
                UCControlCommon.GetRefSelectAndFromSql(pFieldDicInfo, ref  fromSql, ref  selectSql);
            }
            else
            {
                selectSql += sTableCode + "." + sFieldCode + " as " + sTableCode + "__" + sFieldCode + ",";
            }

        }
    }
}
